using Tycho.Parser.Peg;

namespace Tycho.Grammar {
    class DelimitedRuleCompiler : IRuleCompiler {
        private readonly IRuleCompiler RuleCompiler;

        public DelimitedRuleCompiler (IRuleCompiler ruleCompiler) {
            RuleCompiler = ruleCompiler;
        }

        public IRule Compile (ITerm term, ProductionCompilerContext context, ICaptureCounter captureCounter) {
            var compositeTerm = (CompositeTerm) term;

            var rule = compositeTerm.SubTerms["rule"];
            var delimiter = compositeTerm.SubTerms["delimiter"];

            var itemRule = RuleCompiler.Compile (rule, context, captureCounter.CreateMultipleCaptureScope ());
            var delimiterRule = RuleCompiler.Compile (delimiter, context, captureCounter);

            if (itemRule is NamedRule && delimiterRule is KeywordRule) {
                var namedItemRule = (NamedRule) itemRule;

                namedItemRule.Production = new RecoveryProduction (namedItemRule.Production,
                                                                   ((KeywordRule) delimiterRule).Production);
            }

            return new DelimitedRule (itemRule, delimiterRule);
        }
    }
}